package com.youlin.stomp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Controller;

@Controller
public class ReceiveController {

    @Autowired(required = false)
    private SimpMessagingTemplate messagingTemplate;

    @MessageMapping("/zxcv")
    @SendTo("/topic/notice")
    public String all(String message) {
        System.out.printf("\033[34m *** 来自客户端的消息 ===>> %s *** \033[0m\n", message);
        return message;
    }

    @MessageMapping("/chat.{name}")
    @SendToUser(value = "/queue/reply", broadcast = false) // 默认发送给当前请求用户
    public String chat(@DestinationVariable String name, String message, MessageHeaders messageHeaders) {
        MyPrincipal simpUser = messageHeaders.get("simpUser", MyPrincipal.class);
        String userName = simpUser.getName();
        String format = String.format("%s ===>> %s : %s", userName, name, message);
        messagingTemplate.convertAndSendToUser(name, "/queue/reply", format);
        System.out.printf("\033[34m *** 来自客户端的消息 ===>> %s *** \033[0m\n", format);
        return message;
    }

}

